/*
 * @Author: Lu junwen
 * @Date: 2022-04-06 17:42:32
 * @LastEditors: Lu junwen
 * @LastEditTime: 2022-05-19 03:54:09
 * @FilePath: \vue-shop-app-customer\src\store\address\address.js
 */
export default {
  namespaced: true,
  state: {
    addressData: [
      {
        id: "1",
        name: "张三",
        tel: "13000000000",
        address: "浙江省杭州市西湖区,文三路138号东方通信大厦7楼501室",
        isDefault: true,
      },
      {
        id: "2",
        name: "李四",
        tel: "1310000000",
        address: "浙江省杭州市拱墅区,莫干山路 50 号",
        isDefault: false,
      },
    ],
  },
  mutations: {
    ADD_ADDRESS(state, payload) {
      let obj = state.addressData[state.addressData.length - 1]
      payload.id = Number(obj.id) + 1 + ''
      // if (payload.isDefault === true) {
      //   for (let index = 0; index < state.addressData.length; index++) {
      //     state.addressData[index].isDefault = false;
      //   }
      // }
      state.addressData.push(payload)
    },
    UPDATE_ADDRESS(state, payload) {
      for (let index = 0; index < state.addressData.length; index++) {
        const element = state.addressData[index];
        // if (payload.isDefault === true) {
        state.addressData[index].isDefault = false;
        if (element.id === payload.id) {
          state.addressData[index] = payload
          // state.addressData[index].tel = payload.tel
          // state.addressData[index].address = payload.address
        }
        // } else {
        // if (element.id === payload.id) {
        // state.addressData[index].name = payload.name
        // state.addressData[index].tel = payload.tel
        // state.addressData[index].address = payload.address
        // }
        // }

      }
    },
    DELETE_ADDRESS(state, payload) {
      for (let index = 0; index < state.addressData.length; index++) {
        const element = state.addressData[index];
        if (element.id === payload.id) {
          state.addressData.splice(index, 1)
          // if (payload.isDefault === true) {
          // state.addressData[0].isDefault = true
          // }
        }
      }
    }
  },
  actions: {
    addAddress(context, params) {
      context.commit('ADD_ADDRESS', params)
    },
    updateAddress(context, params) {
      context.commit('UPDATE_ADDRESS', params)
    },
    deleteAddress(context, params) {
      context.commit('DELETE_ADDRESS', params)
    }
  }
}